<?php

/**
 * @version $Id: profile.php 428 2012-03-28 12:03:35Z lnmtrung@gmail.com $
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
jimport('joomla.application.component.model');  
jimport('joomla.application.component.modelform');
jimport('joomla.event.dispatcher');

class WrdModelProfile extends WrdModel { 
	
    var $_data;
	var $_id;
	var $_total = null;
	var $_pagination = null;
	var $_limit = null;
	var $_limitstart = null;

	public function __construct(){
		
		parent::__construct();
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		$this->_limit = $mainframe->getUserStateFromRequest( $context.$view.'limit', 'limit', $mainframe->getCfg('list_limit'), 20);
		$this->_limitstart = $mainframe->getUserStateFromRequest( $context.$view.'limitstart', 'limitstart', 0 );

		$this->setState('limit', $this->_limit);
		$this->setState('limitstart', $this->_limitstart);
	}

	public function getData(){
		
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		$search    = $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string');
		
		$filter_order     		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
		$filter_order_Dir 		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
		$q = "
           ( SELECT
				CONCAT(`p`.l_name, ' ', `p`.f_name) AS `full_name`,
                u.name     AS created_per,
				outlet.name  AS name,job.name AS job_name,p.id,p.p_o_u,
                p.prefix,p.f_name,p.l_name,p.dob,p.phone,p.member_id,p.user_id,p.company_name,p.p_email,
				p.job,p.outlet_date,p.created_date,p.serial_no,
            FROM #__wrd_profile `p`
			LEFT JOIN #__wrd_outlets AS outlet
              ON p.outlet_code = outlet.code  
            LEFT JOIN #__users AS u
              ON u.id = p.created_id
			LEFT JOIN #__wrd_job AS job
              ON job.id = p.job
			)  
        ";
		
		$query = $this->_buildQuery();
		//echo $query;
		if (empty($this->_data)){
			$query = $this->_buildQuery();
			if(($filter_order == "point")&&($search == '')){
				if($filter_order_Dir == 'desc'){
					$query = $q.' ORDER BY `p`.p_o_u DESC';
				}
				elseif($filter_order_Dir == 'asc'){
					$query = $q." ORDER BY `p`.p_o_u asc";
				}
			}
			//echo $query;
			$this->_db->setQuery( $query, $this->_limitstart, $this->_limit );
			$this->_data = $this->_db->loadObjectList();
		}
		$data = $this->_data;
		return $data;
	}

	public function _buildQuery(){
        
        /**** Pre Init ****/
        $mainframe = &JFactory::getApplication();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        
        /**** Build condition ****/
        $search             = $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string');
      
		$searchfillter      = $mainframe->getUserStateFromRequest( $context.$view.'searchFillter','searchfillter');
		$datefillter      = $mainframe->getUserStateFromRequest( $context.$view.'dateFillter','dateFillter');
       
		$profilefillter     = $mainframe->getUserStateFromRequest( $context.$view.'profilefillter','profilefillter',0,'int' );
        $filter_pick_up_outlet     = $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','string' );
        $filter_order     		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
		$filter_order_Dir 		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
		
		$allDate = self::getFilterDate($mainframe);    
        $post = JRequest::get('post');        
        $search        = JString::strtolower( $search ); 

        $condition = ' WHERE 1 = 1 ';
        if($search != '') {
            $seach_parse = $this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
            $searchName = true;
            $filterField = array();
			
		   if(!empty($searchfillter)) {
                $searchName = false;            
                foreach($searchfillter as $item){
                    if($item == 0) {
                    
						$searchName = true;
                        $search = $this->_db->getEscaped( $search, true );
						$search = explode(' ', $search);
                        
						$lastName = implode("%') OR (p.l_name LIKE '%", $search);
                        $lastName = " OR (p.l_name LIKE '%".$lastName."%') ";
                        
                        $firstName = implode("%') OR (p.f_name LIKE '%", $search);
                        $firstName = " (p.f_name LIKE '%".$firstName."%') ";
                                                
                        $filterField['id'] = ' (p.member_id LIKE '.$seach_parse.') ';
                        $filterField['phone'] = ' (p.phone LIKE '.$seach_parse.') ';
                        $filterField['companyName'] = ' (p.company_name LIKE '.$seach_parse.') ';
                        $filterField['email'] = ' (p.p_email LIKE '.$seach_parse.' OR p.alternative_email LIKE '.$seach_parse.') ';
                        $filterField['fullName'] = ' ( '.$firstName.' '.$lastName.' ) ';
                        
                        break;
                    }
                    else if($item == 1) {
                       
						$search = $this->_db->getEscaped( $search, true );

                        $filterField['fullName'] = " (CONCAT(f_name,' ',l_name) LIKE '%".$search."%') OR (CONCAT(l_name,' ',f_name) LIKE '%".$search."%') ";
                        
                        $searchName = true;
                    }
                    else if($item == 2) {
					
                        $filterField['id'] = ' (p.member_id LIKE '.$seach_parse.') ';
                    }
                    else if($item == 3) {
                        $filterField['phone'] = ' (p.phone LIKE '.$seach_parse.') ';
                    }                    
                    else if($item == 4) {
                        $filterField['companyName'] = ' (p.company_name LIKE '.$seach_parse.') ';
                    }
                    else if($item == 5) {
                        $filterField['email'] = ' (p.p_email LIKE '.$seach_parse.' OR p.alternative_email LIKE '.$seach_parse.') ';
                    }   
                }    
            }
            else {
                $search = $this->_db->getEscaped( $search, true );
                $search = explode(' ', $search);
                $lastName = implode("%') OR (p.l_name LIKE '%", $search);
                $lastName = " OR (p.l_name LIKE '%".$lastName."%') ";

                $firstName = implode("%') OR (p.f_name LIKE '%", $search);
                $firstName = " (p.f_name LIKE '%".$firstName."%') ";

			    $filterField['id'] = ' (p.member_id LIKE '.$seach_parse.') ';
                $filterField['phone'] = ' (p.phone LIKE '.$seach_parse.') ';
                $filterField['companyName'] = ' (p.company_name LIKE '.$seach_parse.') ';
                $filterField['email'] = ' (p.p_email LIKE '.$seach_parse.' OR p.alternative_email LIKE '.$seach_parse.') ';
                $filterField['fullName'] = ' ( '.$firstName.' '.$lastName.' ) ';
            }
            
            if(!empty($filterField)) {
                $filterFieldText = implode(' OR ', $filterField);
                $condition .= " AND (".$filterFieldText.") ";
            }
            
            if($searchName == true && $seach_parse != '') {
                unset($filterField['fullName']);
                $filterFieldText = implode(' OR ', $filterField);
            }
            
            $order_fields = $mainframe->getUserStateFromRequest( $context.$view.'order_field','order_field');
         
			if(!empty($order_fields)){
                $order_fields = implode( ',', $order_fields ) ;
            }else{
                $order_fields = 'id' ;
            }
        }

		if ( $profilefillter != 0 ){
			$condition .= ' AND p.status_of_card = '.$profilefillter.' ';
			
		}
		
		if($filter_pick_up_outlet != ""){
			$condition .= ' AND (p.pick_up_at = "'.$filter_pick_up_outlet.'") ';
		} 
		
		if(!empty($datefillter)){
				foreach($datefillter as $item){
					if($item == 1) {
						$condition .= ' AND p.dob BETWEEN "'.($allDate['birthdayFrom'][0].'-'.$allDate['birthdayFrom'][1].'-'.$allDate['birthdayFrom'][2]).'" AND "'.($allDate['birthdayTo'][0].'-'.$allDate['birthdayTo'][1].'-'.$allDate['birthdayTo'][2]).'" ';
					}
					if($item == 2) {
						$condition .= ' AND p.created_date BETWEEN "'.($allDate['birthdayFrom'][0].'-'.$allDate['birthdayFrom'][1].'-'.$allDate['birthdayFrom'][2]).'" AND "'.($allDate['birthdayTo'][0].'-'.$allDate['birthdayTo'][1].'-'.$allDate['birthdayTo'][2]).'" ';
					}
					if($item==0){
						$condition .= ' AND(( p.dob BETWEEN "'.($allDate['birthdayFrom'][0].'-'.$allDate['birthdayFrom'][1].'-'.$allDate['birthdayFrom'][2]).'" AND "'.($allDate['birthdayTo'][0].'-'.$allDate['birthdayTo'][1].'-'.$allDate['birthdayTo'][2]).'" )';
						$condition .= '||';
						$condition .= ' ( p.created_date BETWEEN "'.($allDate['birthdayFrom'][0].'-'.$allDate['birthdayFrom'][1].'-'.$allDate['birthdayFrom'][2]).'" AND "'.($allDate['birthdayTo'][0].'-'.$allDate['birthdayTo'][1].'-'.$allDate['birthdayTo'][2]).'" ))';
					}
				}
			}
		
        
		$query = "
            SELECT
				CONCAT(`p`.l_name, ' ', `p`.f_name) AS `full_name`,
                u.name     AS created_per,
				outlet.name  AS name,job.name AS job_name,p.id,p.p_o_u,
                p.prefix,p.f_name,p.l_name,p.dob,p.phone,p.member_id,p.user_id,p.company_name,p.p_email,
				p.job,p.outlet_date,p.created_date,p.serial_no
            FROM #__wrd_profile `p`
			LEFT JOIN #__wrd_outlets AS outlet
              ON p.outlet_code = outlet.code  
            LEFT JOIN #__users AS u
              ON u.id = p.created_id
			LEFT JOIN #__wrd_job AS job
              ON job.id = p.job
        ";
		
		if(!(($filter_order == "point")&&($search == ''))){
			$query .= $condition.' ';
			$order_fields = $mainframe->getUserStateFromRequest( $context.$view.'order_field','order_field');
			$orderby 			= $this->_buildContentOrderBy();
			$query .= $orderby;
		}
		
        return $query;
    }
    
    /*** Old version ***/
	public function _buildQueryTemp(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$orderby 			= $this->_buildContentOrderBy();
		
		$search 			= $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string');
		$searchfillter 		= $mainframe->getUserStateFromRequest( $context.$view.'searchFillter','searchfillter');
		
		$profilefillter 	= $mainframe->getUserStateFromRequest( $context.$view.'profilefillter','profilefillter',0,'int' );
		$filter_pick_up_outlet 	= $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','string' );
		
		$filter_byfrom = $mainframe->getUserStateFromRequest( $context.$view.'byfrom','byfrom','','int' );
		$filter_bmfrom = $mainframe->getUserStateFromRequest( $context.$view.'bmfrom','bmfrom','','int' );
		$filter_bdfrom = $mainframe->getUserStateFromRequest( $context.$view.'bdfrom','bdfrom','','int' );
		$filter_byto   = $mainframe->getUserStateFromRequest( $context.$view.'byto','byto','','int' );
		$filter_bmto   = $mainframe->getUserStateFromRequest( $context.$view.'bmto','bmto','','int' );
		$filter_bdto   = $mainframe->getUserStateFromRequest( $context.$view.'bdto','bdto','','int' );
		
		$filter_cyfrom = $mainframe->getUserStateFromRequest( $context.$view.'cyfrom','cyfrom','','int' );
		$filter_cmfrom = $mainframe->getUserStateFromRequest( $context.$view.'cmfrom','cmfrom','','int' );
		$filter_cdfrom = $mainframe->getUserStateFromRequest( $context.$view.'cdfrom','cdfrom','','int' );
		$filter_cyto   = $mainframe->getUserStateFromRequest( $context.$view.'cyto','cyto','','int' );
		$filter_cmto   = $mainframe->getUserStateFromRequest( $context.$view.'cmto','cmto','','int' );
		$filter_cdto   = $mainframe->getUserStateFromRequest( $context.$view.'cdto','cdto','','int' );
		
		$filter_pyfrom = $mainframe->getUserStateFromRequest( $context.$view.'pyfrom','pyfrom','','int' );
		$filter_pmfrom = $mainframe->getUserStateFromRequest( $context.$view.'pmfrom','pmfrom','','int' );
		$filter_pdfrom = $mainframe->getUserStateFromRequest( $context.$view.'pdfrom','pdfrom','','int' );
		$filter_pyto   = $mainframe->getUserStateFromRequest( $context.$view.'pyto','pyto','','int' );
		$filter_pmto   = $mainframe->getUserStateFromRequest( $context.$view.'pmto','pmto','','int' );
		$filter_pdto   = $mainframe->getUserStateFromRequest( $context.$view.'pdto','pdto','','int' );
		
		$post = JRequest::get('post');		
		$search 	   = JString::strtolower( $search );
		
		$where = array();
		if ( $search ){
			$seach_parse = $this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
			$other_field = array() ;
			if(count($searchfillter) > 0){
				foreach ($searchfillter as $row){
					if($row == 1){
						$other_field[] = '(p.name_on_card LIKE '.$seach_parse.')';
						continue;
					}
					if($row == 2){
						$other_field[] = '(p.member_id LIKE '.$seach_parse.')';
						continue;
					}
					if($row == 3){
						$other_field[] = '(p.phone LIKE '.$seach_parse.')';
						continue;
					}
					if($row == 4){
						$other_field[] = '(p.company_name LIKE '.$seach_parse.')'; 
						continue;
					}
					if($row == 5){
						$other_field[] = '(p.p_email LIKE '.$seach_parse.')';
						continue;
					}
				}
			}
			
			$other_field = implode( '||', $other_field ) ;
			if(!empty($other_field)){
				$where[] = '('.$other_field.')'; 
			}else{
				$where[] = '(
				(p.phone LIKE '.$seach_parse.') || 
				(p.company_name LIKE '.$seach_parse.') || 
				(p.member_id LIKE '.$seach_parse.') ||
				(p.name_on_card LIKE '.$seach_parse.') || 
				(p.p_email LIKE '.$seach_parse.')
				)';
			}
		}
		
		if ( $profilefillter != 0 ){
			$where[] = 'p.status_of_card = '.$profilefillter;
		}
		if($filter_pick_up_outlet != ""){
			$where[] = ' p.pick_up_at = "'.$filter_pick_up_outlet.'"';
		}
		if(empty($filter_byfrom)){
			$filter_byfrom = 'YEAR(p.dob)' ;
		}
		if(empty($filter_byto)){
			$filter_byto = 'YEAR(p.dob)' ;
		}
		if(empty($filter_bmfrom)){
			$filter_bmfrom = 'MONTH(p.dob)' ;
		}
		if(empty($filter_bmto)){
			$filter_bmto = 'MONTH(p.dob)' ;
		}
		if(empty($filter_bdfrom)){
			$filter_bdfrom = 'DAY(p.dob)' ;
		}
		if(empty($filter_bdto)){
			$filter_bdto = 'DAY(p.dob)' ;
		}
		$where[] = 'p.dob >= (concat('.$filter_byfrom.',"-",'.$filter_bmfrom.',"-",'.$filter_bdfrom.')) and p.dob <=(concat('.$filter_byto.',"-",'.$filter_bmto.',"-",'.$filter_bdto.'))';
		

		if(empty($filter_cyfrom)){
			$filter_cyfrom = 'YEAR(p.created_date)' ;
		}
		if(empty($filter_cyto)){
			$filter_cyto = 'YEAR(p.created_date)' ;
		}
		if(empty($filter_cmfrom)){
			$filter_cmfrom = 'MONTH(p.created_date)' ;
		}
		if(empty($filter_cmto)){
			$filter_cmto = 'MONTH(p.created_date)' ;
		}
		if(empty($filter_cdfrom)){
			$filter_cdfrom = 'DAY(p.created_date)' ;
		}
		if(empty($filter_cdto)){
			$filter_cdto = 'DAY(p.created_date)' ;
		}
		$where[] = 'p.created_date >= (concat('.$filter_cyfrom.',"-",'.$filter_cmfrom.',"-",'.$filter_cdfrom.')) and p.created_date <=(concat('.$filter_cyto.',"-",'.$filter_cmto.',"-",'.$filter_cdto.'))';
		
		if(empty($filter_pyfrom)){
			$filter_pyfrom = 'YEAR(p.pick_up_date)' ;
		}
		if(empty($filter_pyto)){
			$filter_pyto = 'YEAR(p.pick_up_date)' ;
		}
		if(empty($filter_pmfrom)){
			$filter_pmfrom = 'MONTH(p.pick_up_date)' ;
		}
		if(empty($filter_pmto)){
			$filter_pmto = 'MONTH(p.pick_up_date)' ;
		}
		if(empty($filter_pdfrom)){
			$filter_pdfrom = 'DAY(p.pick_up_date)' ;
		}
		if(empty($filter_pdto)){
			$filter_pdto = 'DAY(p.pick_up_date)' ;
		}
		$where[] = 'p.pick_up_date >= (concat('.$filter_pyfrom.',"-",'.$filter_pmfrom.',"-",'.$filter_pdfrom.')) and p.pick_up_date <=(concat('.$filter_pyto.',"-",'.$filter_pmto.',"-",'.$filter_pdto.'))';
		
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
		
		$order_fields = $mainframe->getUserStateFromRequest( $context.$view.'order_field','order_field');
		if(!empty($order_fields)){
			$order_fields = implode( ',', $order_fields ) ;
		}else{
			$order_fields = 'id' ;
		}
        
        $extraQuery = "";
        if(!empty($searchfillter)) {
            $searchName = false;            
            foreach($searchfillter as $item){
                if($item == 0 ||$item == 1) {
                    $searchName = true;
                }
            }    
        }
        else {
            $searchName = true;
        }
        
        if($searchName == true && $seach_parse != '') {
            $extraQuery = "
                GROUP BY `p`.user_id
                HAVING `full_name` LIKE ".$seach_parse."
            ";
        }
		
		$query = ' SELECT  
			p.id, p.prefix, p.user_id, p.f_name, p.l_name, p.gender, p.published, p.created_date, p.dob, p.member_id, p.phone, p.address,
			p.c_addr, p.c_info, p.step, p.website, p.skype, p.yahoo, p.gtalk, p.social, p.msn, p.modify_date, p.job, job.name as job_name, p.job_prefix, p.o_job, u.name as created_per, CONCAT(`p`.l_name, " ", `p`.f_name) AS `full_name`,
			mu.name as modify_person, pu.name,pu.email, p.industry, p.department, p.o_department, p.education, p.o_club, p.income, p.hobbies, p.c_country, p.c_city, p.c_distric,
			ctry.name as ctry_country, cty.name as cty_city, dtric.name as dis_distric, p.referer, p.referer_phone, p.status, p.country_code, p.p_email, p.nationality,
			p.name_on_card, p.company_name, p.modify_by, p.delivery_date, p.pick_up_date 
			                             
			FROM #__wrd_profile as p 
			LEFT JOIN #__users as pu ON pu.id = p.user_id 
			LEFT JOIN #__users as u ON u.id = p.created_id
			LEFT JOIN #__users as mu ON mu.id = p.modify_by
			LEFT JOIN #__wrd_country as ctry ON ctry.id = p.country
			LEFT JOIN #__wrd_city as cty ON cty.id = p.city
			LEFT JOIN #__wrd_job as job ON job.id = p.job
			LEFT JOIN #__wrd_distric as dtric ON dtric.id = p.distric' 
		. $where
        .$extraQuery;
		if(!empty($order_fields)){
			$query .= ' ORDER BY '.$order_fields.' DESC' ;	
		}

		return $query;
	}

	public function _buildContentOrderBy(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$filter_order     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_author','filter_order','created_date' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir',  'filter_order_Dir', 'DESC' );
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
		return $orderby;
	}
	
	public function getTotal(){
		
		if (empty($this->_total)){
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}

	public function getPagination(){
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->_limitstart, $this->_limit );
		}
		return $this->_pagination;
	}

    private function getFilterDate($mainframe){
    	$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
        $filter_byfrom = $mainframe->getUserStateFromRequest( $context.$view.'byfrom','byfrom','','int' );
        $filter_bmfrom = $mainframe->getUserStateFromRequest( $context.$view.'bmfrom','bmfrom','','int' );
        $filter_bdfrom = $mainframe->getUserStateFromRequest( $context.$view.'bdfrom','bdfrom','','int' );
        $filter_byto   = $mainframe->getUserStateFromRequest( $context.$view.'byto','byto','','int' );
        $filter_bmto   = $mainframe->getUserStateFromRequest( $context.$view.'bmto','bmto','','int' );
        $filter_bdto   = $mainframe->getUserStateFromRequest( $context.$view.'bdto','bdto','','int' );
        
        $filter_cyfrom = $mainframe->getUserStateFromRequest( $context.$view.'cyfrom','cyfrom','','int' );
        $filter_cmfrom = $mainframe->getUserStateFromRequest( $context.$view.'cmfrom','cmfrom','','int' );
        $filter_cdfrom = $mainframe->getUserStateFromRequest( $context.$view.'cdfrom','cdfrom','','int' );
        $filter_cyto   = $mainframe->getUserStateFromRequest( $context.$view.'cyto','cyto','','int' );
        $filter_cmto   = $mainframe->getUserStateFromRequest( $context.$view.'cmto','cmto','','int' );
        $filter_cdto   = $mainframe->getUserStateFromRequest( $context.$view.'cdto','cdto','','int' );
        
        $filter_pyfrom = $mainframe->getUserStateFromRequest( $context.$view.'pyfrom','pyfrom','','int' );
        $filter_pmfrom = $mainframe->getUserStateFromRequest( $context.$view.'pmfrom','pmfrom','','int' );
        $filter_pdfrom = $mainframe->getUserStateFromRequest( $context.$view.'pdfrom','pdfrom','','int' );
        $filter_pyto   = $mainframe->getUserStateFromRequest( $context.$view.'pyto','pyto','','int' );
        $filter_pmto   = $mainframe->getUserStateFromRequest( $context.$view.'pmto','pmto','','int' );
        $filter_pdto   = $mainframe->getUserStateFromRequest( $context.$view.'pdto','pdto','','int' );
        
        return array(
            'birthdayFrom' => array(trim($filter_byfrom), trim($filter_bmfrom), trim($filter_bdfrom)),
            'birthdayTo' => array(trim($filter_byto), trim($filter_bmto), trim($filter_bdto)),
            
            'createdFrom' => array(trim($filter_cyfrom), trim($filter_cmfrom), trim($filter_cdfrom)),
            'createdTo' => array(trim($filter_cyto), trim($filter_cmto), trim($filter_cdto)),
            
            'pickUpFrom' => array(trim($filter_pyfrom), trim($filter_pmfrom), trim($filter_pdfrom)),
            'pickUpTo' => array(trim($filter_pyto), trim($filter_pmto), trim($filter_pdto))  
        );
    }    
    
	public function delete($cid = array()){
		$result = false;
		if (count( $cid )){
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = 'SELECT user_id FROM #__wrd_profile WHERE id IN ('.$cids.')';
			$this->_db->setQuery($query);
			$rs = $this->_db->loadObjectList();
			if(count($rs) > 0){	
				foreach ($rs as $key => $value) {
					$db = JFactory::getDbo();
					$query = 'SELECT member_id FROM #__wrd_profile WHERE user_id = '.$value->user_id; 
					$db->setQuery($query);
					$member_id = $db->loadObjectList();
					
					$sql = "UPDATE `#__wrd_lucky_num` SET `available` = '1' WHERE `#__wrd_lucky_num`.`number` =".$member_id[0]->member_id;
					$db->setQuery($sql);
					$db->query();
					
					$query = 'DELETE FROM #__wrd_profile WHERE user_id = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
					
					$query = 'DELETE FROM #__users WHERE id = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();

					$query = 'DELETE FROM #__user_usergroup_map  WHERE user_id = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
								
					$query = 'DELETE FROM #__wrd_spending_summary  WHERE member_id  = '.$member_id[0]->member_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
					
					$query = 'DELETE FROM #__wrd_point  WHERE user_id = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
					
					$query = 'DELETE FROM #__wrd_points_summary  WHERE user_id = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
					
					$query = 'DELETE FROM #__wrd_redemption  WHERE user_id = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
					
					$query = 'DELETE FROM #__session  WHERE userid = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
					
					$query = 'DELETE FROM #__wrd_log_register  WHERE id = '.$value->user_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();
					
					$query = 'DELETE FROM #__wrd_discount_profile  WHERE member_id = '.$member_id[0]->member_id ;
					$this->_db->setQuery( $query );
					$this->_db->query();

				}
			}else{
				return false;
			}
		}

		return true;
	}
 
	public function publish($cid = array(), $publish = 1){
		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__wrd_profile '
				. ' SET published = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
    
     //save to table $nametable
    public function store($post,$tablename){
		$profile = JTable::getInstance($tablename, 'TableWrd');
	
        $profile->load();
        $profile->bind($post);
		if ($profile->store()) {
			return $profile->id;
		} else {
			return 0;
		}
  	}
  	
  	public function getList(){
  		$query = 'SELECT id AS value, state AS text'
		. ' FROM #__wrd_profile WHERE published=1';

		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
  	}

	public function getUserList(){

		$query = 'SELECT a.created_id as value , b.username as text FROM #__wrd_profile a LEFT JOIN #__users b ON a.created_id = b.id GROUP BY a.created_id';
		
		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
	}
  	
  	public function getItem($id){
  	
		$query = '
  		SELECT a.*,b.username
  		FROM #__wrd_profile as a 
  		INNER JOIN #__users as b ON a.user_id = b.id 
  		WHERE a.id = '.$id;
		
		$this->_db->setQuery($query);
		return $this->_db->loadObject();
  	}
	
  	public function getModifyBy($id){
		$query = '
  		SELECT name,username
  		FROM #__users 
  		WHERE id = '.$id;
		
		$this->_db->setQuery($query);
	
		return $this->_db->loadObject();
	}
	
	public function send_email($cid = array(), $type = 'send_mail_verify'){
		
		$db = JFactory::getDbo();
		$staff = JFactory::getUser();
		
		if (count( $cid ))
		{
			
			if($type == 'send_mail_verify'){
				$type = 'verify' ;
			}else if($type == 'send_mail_birth'){
				
				$type = 'birthday' ;
				
				$this->sendEmailNOtificationEmailBirthday($cid,$staff);
				
			}else if($type == 'send_pickup_notice'){
				$type = 'pickup_notice' ;
			}else if($type == 'send_mail_renew'){
				$type = 'renew' ;
			}
			JArrayHelper::toInteger($cid);
			
			foreach($cid as $k=>$v){
				
				$user_profile = $this->getItem($v);
				$sql = ' select name from #__wrd_lprefer where `id` = "'.$user_profile->lprefer.'"' ;
				$db->setQuery($sql) ;
				$rs = $db->loadObject();
				if(!empty($user_profile->p_email)){
					$this->send_email_template($type,$user_profile, $rs->name);
				}else{ 
					$user_email = $this->getUserEmail($user_profile->user_id) ;
					$user_profile->p_email = $user_email ;
					
					if(!empty($user_profile->p_email)){
						$this->send_email_template($type,$user_profile, $rs->name);
					}
				}
			}
		}
		
		return true;
	}
	
	public function sendEmailNOtificationEmailBirthday($cid = array(),$staff){

		if( count($cid) <= 0 ) return false;
		$sql = "SELECT * from #__wrd_cemail where `id` = 14 " ;
		$db = JFactory::getDbo();
		$db->setQuery($sql) ;
		$rs = $db->loadObject();
		
		
		if(!empty($rs)){
				
			$list_member_birthday = "";
			
			foreach($cid as $k=>$v){
				
				$user_profile = $this->getItem($v);
				
				$list_member_birthday .= "<a href=' ".JURI::root() ."administrator/index.php?option=com_wrd&controller=profile&id=".$user_profile->id."&layout=form' target='_blank' > ".$user_profile->member_id." </a>&nbsp;&nbsp;";
			}
			
			$emailBody = $rs->template ;

			$emailBody = str_replace('{username}', $staff->username, $emailBody);
			
			$emailBody = str_replace('{today}',date("d-m-Y H:i:s"), $emailBody);
			
			$emailBody = str_replace('{number}', count($cid), $emailBody);
			
			$emailBody = str_replace('{list_member_birthday}',$list_member_birthday , $emailBody);
			

			$emailSubject = $rs->subject;
			
			$mailFrom = "info@wmcvip.vn";
			
			$to = explode(',', $rs->email);
			
			foreach($to as $key => $email):
			
				$return = JUtility::sendMail($mailFrom, 'WMCVip', $email, $emailSubject, $emailBody,1);
					
				if ($return !== true) {
					
					$this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED'));
					
				}
				
			 endforeach;
		
		}
		
		return true;
		
	}	
	
	public function send_email_template($type='verify',$user_profile,$lang='English'){
		
		$db = JFactory::getDbo();
		
		if($type=='reset_pass'){
			$user_profile = (array)$user_profile;	
			$password = $user_profile['member_id'].$user_profile['year_birth'];
		
			$sql = 'select * from #__wrd_cemail where `action` = "'.$type.'" AND id='. 14 ;
			$db->setQuery($sql) ;
			$rs = $db->loadObject();
						
			if(!empty($rs)){
			
				if(($user_profile['country']==249) || ($user_profile['nationality']==249)){
					$emailBody = $rs->template_vi ;
				}
				else {
					$emailBody = $rs->template ;
				}

				$emailBody = str_replace('{line-break}', '<br />', $emailBody);
				$emailBody = str_replace('{member_id}',$user_profile['member_id'], $emailBody);
				$emailBody = str_replace('{email}', $user_profile['p_email'], $emailBody);
				$emailBody = str_replace('{password}', $password, $emailBody);
				$link = JURI::root().'index.php?option=com_wrd&view=profile&Itemid=139';
				$emailBody = str_replace('{link}', $link, $emailBody);
				$emailSubject = $rs->subject;
				$mailFrom = $rs->email;
				
				$return = JUtility::sendMail($mailFrom, 'WMC Rewards - Reset Password', $user_profile['p_email'], $emailSubject, $emailBody,1);
			}
			return true;
		}
		
		if(!empty($user_profile)){

			$sql = ' select * from #__wrd_cemail where `action` = "'.$type.'"' ;
			$db->setQuery($sql) ;
			$rs = $db->loadObject();
			$config = JFactory::getConfig();
			
			$data['fromname']	= $config->get('fromname');
  			$data['mailfrom']	= $config->get('mailfrom');
  			$data['sitename']	= $config->get('sitename');
			
			if(!empty($rs)){
				if($user_profile->distric == 5){
					if($lang == 'Vietnamese'){
						$emailBody = $rs->template_vi ;
					}else{
						$emailBody = $rs->template ;
					}
				}else{
					if($lang == 'Vietnamese'){
						$emailBody = $rs->template_vi ;
					}else{
						$emailBody = $rs->template ;
					}
				}
				$cc = split(',', $rs->email) ;
				if($type=='verify'){
					$emailBody = str_replace('{line-break}', '<br />', $emailBody);
					$emailBody = str_replace('{f_name}', $user_profile->f_name, $emailBody);
					$emailBody = str_replace('{l_name}', $user_profile->l_name, $emailBody);
					$emailBody = str_replace('{name_on_card}', $user_profile->name_on_card, $emailBody);
					$emailBody = str_replace('{dob}', $user_profile->dob, $emailBody);
					$emailBody = str_replace('{phone}', $user_profile->phone, $emailBody);
					$emailBody = str_replace('{address}', $user_profile->address, $emailBody);
					$coutry_name = $this->getCountryName($user_profile->country) ;
					$emailBody = str_replace('{country}',$coutry_name, $emailBody);
					$city_name = $this->getCityName($user_profile->city) ;
					$emailBody = str_replace('{city}',$city_name, $emailBody);
					$district_name = $this->getDistrictName($user_profile->distric) ;
					$emailBody = str_replace('{district}',$district_name, $emailBody);
					$outlet_name = $this->getOutletName($user_profile->pick_up_at) ;
					$outlet_address = $this->getOutletAddress($user_profile->pick_up_at,$lang) ;
					$emailBody = str_replace('{outlet_address}', $outlet_address, $emailBody);
					$emailBody = str_replace('{pick_up_at}',$outlet_name, $emailBody);
					$emailSubject = empty($rs->subject) ? 'Verify at '.$data['sitename'] : $rs->subject ;
				}else if($type=='renew'){
					$emailBody = str_replace('{line-break}', '<br />', $emailBody);
					$emailBody = str_replace('{username}', $user_profile->username, $emailBody);
					$emailBody = str_replace('{user_id}', sha1($user_profile->user_id), $emailBody);
					$emailBody = str_replace('{f_name}', $user_profile->f_name, $emailBody);
					$emailBody = str_replace('{l_name}', $user_profile->l_name, $emailBody);
					$emailBody = str_replace('{name_on_card}', $user_profile->name_on_card, $emailBody);
					$emailBody = str_replace('{dob}', $user_profile->dob, $emailBody);
					$emailBody = str_replace('{phone}', $user_profile->phone, $emailBody);
					$emailBody = str_replace('{address}', $user_profile->address, $emailBody);
					$coutry_name = $this->getCountryName($user_profile->country) ;
					$emailBody = str_replace('{country}',$coutry_name, $emailBody);
					$city_name = $this->getCityName($user_profile->city) ;
					$emailBody = str_replace('{city}',$city_name, $emailBody);
					$district_name = $this->getDistrictName($user_profile->distric) ;
					$emailBody = str_replace('{district}',$district_name, $emailBody);
					$outlet_name = $this->getOutletName($user_profile->pick_up_at) ;
					$outlet_address = $this->getOutletAddress($user_profile->pick_up_at,$lang) ;
					$emailBody = str_replace('{outlet_address}', $outlet_address, $emailBody);
					$emailBody = str_replace('{pick_up_at}',$outlet_name, $emailBody);
					$emailSubject = empty($rs->subject) ? 'Verify at '.$data['sitename'] : $rs->subject ;
				}else if($type=='birthday'){
					list($year, $month, $day) = split('[/.-]', $user_profile->dob) ;
					$emailBody = str_replace('{line-break}', '<br />', $emailBody);
					$emailBody = str_replace('{f_name}', $user_profile->f_name, $emailBody) ;
					$emailBody = str_replace('{l_name}', $user_profile->l_name, $emailBody) ;
					$emailBody = str_replace('{day}', $day, $emailBody) ;
					$emailBody = str_replace('{month}', $month, $emailBody) ;
					if($user_profile->l_name != '' || $user_profile->f_name != ''){
						$emailSubject = empty($rs->subject) ? 'Happy birthday to '.$user_profile->l_name.' '.$user_profile->f_name : $rs->subject ;
					}else{
						$emailSubject = empty($rs->subject) ? 'Happy birthday to '.$user_profile->p_email : $rs->subject ;
					}
				}else if($type=='pickup_notice'){
					$emailBody = str_replace('{line-break}', '<br />', $emailBody);
					$emailBody = str_replace('{f_name}', $user_profile->f_name, $emailBody);
					$emailBody = str_replace('{l_name}', $user_profile->l_name, $emailBody);
					$emailBody = str_replace('{name_on_card}', $user_profile->name_on_card, $emailBody);
					$emailBody = str_replace('{member_id}', $user_profile->member_id, $emailBody);
					$outlet_name = $this->getOutletName($user_profile->pick_up_at) ;
					$emailBody = str_replace('{outlet_name}', $outlet_name, $emailBody);
					$outlet_address = $this->getOutletAddress($user_profile->pick_up_at,$lang) ;
					$emailBody = str_replace('{outlet_address}', $outlet_address, $emailBody);
					$emailSubject = empty($rs->subject) ? 'Pick up notice email' : $rs->subject ;
				}
				$return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $user_profile->p_email, $emailSubject, $emailBody,1,$cc);
			}
			return true ;
		}
	}
  	
    public function getFullUserProfile($user_id){
        $query = "
            SELECT
                `t`.*,
                `c`.NAME   AS `countryName`,
                `dis`.NAME AS `districName`,
                `ci`.NAME  AS `cityName`,
                `o`.NAME   AS `outlet`,
                `l`.NAME   AS `lang`,
                `n`.NAME   AS `nationalityName`
            FROM #__wrd_profile `t`
                LEFT JOIN #__wrd_lprefer `l`
                  ON `t`.lprefer = `l`.id
                LEFT JOIN #__wrd_country `c`
                  ON `c`.id = `t`.country
                LEFT JOIN #__wrd_country `n`
                  ON `n`.id = `t`.nationality
                left join #__wrd_distric `dis`
                  on `dis`.id = `t`.distric
                left join #__wrd_city `ci`
                  on `ci`.id = `t`.city
                left join #__wrd_outlets `o`
                  on `o`.id = `t`.pick_up_at
            where `t`.user_id = ".intval($user_id)."
        ";
        $this->_db->setQuery($query);
        return $this->_db->loadObject();
    }
      
	public function getUserProfile($user_id){
  		$query = 'SELECT * FROM #__wrd_profile WHERE user_id = '.$user_id;
		$this->_db->setQuery($query);
		return $this->_db->loadObject();
  	}
	public function getCountryName($id=0){
  		$query = 'SELECT name FROM #__wrd_country WHERE id = '.$id;
		$this->_db->setQuery($query);
		$rs = $this->_db->loadObject();
		return $rs->name ;
  	}
	public function getCityName($id=0){
  		$query = 'SELECT name FROM #__wrd_city WHERE id = '.$id;
		$this->_db->setQuery($query);
		$rs = $this->_db->loadObject();
		return $rs->name ;
  	}
	public function getDistrictName($id=0){
  		$query = 'SELECT name FROM #__wrd_distric WHERE id = '.$id;
		$this->_db->setQuery($query);
		$rs = $this->_db->loadObject();
		return $rs->name ;
  	}
	public function getOutletName($id=0){
  		$query = 'SELECT name FROM #__wrd_outlets WHERE code = '.$id;
		$this->_db->setQuery($query);
		$rs = $this->_db->loadObject();
		return $rs->name ;
  	}
	
	public function getOutletAddress($id=0,$lang=''){
  		$query = 'SELECT address FROM #__wrd_outlets WHERE code = '.$id;
		
		$this->_db->setQuery($query);
		$rs = $this->_db->loadObject();
		if($lang == 'Vietnamese'){
			return $rs->address_vi ;
		}else{
			return $rs->address ;
		}
  	}
	
	public function getUserEmail($id=0){
		$query = 'SELECT a.email,b.p_email,alternative_email
		FROM #__users as a 
		LEFT JOIN #__wrd_profile as b on a.id = b.user_id
		WHERE a.id =  '.$id;
		
		$this->_db->setQuery($query);
		$rs = $this->_db->loadObject();
		if($rs->p_email != '') return $rs->p_email ;
		elseif($rs->alternative_email != '') return $rs->alternative_email ;
		else return $rs->email ;
  	}
  	
    public function register($temp,$fe = 0){
		
		$config = JFactory::getConfig();
  		$params = JComponentHelper::getParams('com_users');
		
		$system	= $params->get('new_usertype', 2);
  		$tmp	= new stdClass();
  		$tmp->groups[] = $system;
  		$data = (array)$tmp;
  		
		// Merge in the registration data.
  		foreach ($temp as $k => $v) {
  			$data[$k] = $v;
  		}
		if($data['user_id'] == 0){
  			$user = new JUser;
  			$data['email']		= $data['email1'];
  			$data['name'] 		= $data['member_id'];
  			$data['username'] 	= $data['member_id'];
  		}else{
  			$user = new JUser($data['user_id']);
			if($data[p_email] != '')
				$data['email'] = $data['email1'] =  $data[p_email];
  		}
  		
		// Prepare the data for the user object.
  		$data['profile']	= $data['id'];
  		$data['id'] 		= $data['user_id'];
  		
  		$useractivation 	= $params->get('useractivation');
		
  		if($data['id'] == 0){
  			if (($useractivation == 1) || ($useractivation == 2)){
  				if($fe == 1){
  					$data['block'] = 1 ;
  					jimport('joomla.user.helper');
                    $data['activation'] = JUtility::getHash(JUserHelper::genRandomPassword());
                    $data['block'] = 1;
  				}else{
  					$data['block'] = 0 ;
  				}
  			}
			if(!empty($data['password1'])){
  				$data['password'] = $data['password1'];
  				$data['password_clear'] = $data['password1'];
  			}else{
  				unset($data['password']);
  				unset($data['password1']);
  				unset($data['password2']);
  			}
  		}else{
  			if(!empty($data['password1'])){
  				$data['password'] = $data['password1'];
  				$data['password_clear'] = $data['password1'];
  			}else{
  				unset($data['password']);
  				unset($data['password1']);
  				unset($data['password2']);
  			}
  		}
		
		
  		if (!$user->bind($data)) {
			JFactory::getApplication()->enqueueMessage($user->getError(), 'error');
  			return false;
  		}
		
  		if (!$user->save()) {
			JFactory::getApplication()->enqueueMessage($user->getError(), 'error');
  			return false;
  		}
		
  		if($fe == 1){
  			WrdHelper::activeEmail($data);
  			
  			//update pass word again md5 only
  			$query = 'UPDATE #__users SET password = "'.md5($data['password_clear']).'" WHERE id = '.$user->id;
  			$this->_db->setQuery($query);
  			$this->_db->query();
  			
  			return $user->id;
  		}
		elseif($data['user_id'] == 0){
			$query = 'UPDATE #__users SET password = "'.md5($data['password_clear']).'" WHERE id = '.$user->id;
  			$this->_db->setQuery($query);
  			$this->_db->query();
		}
		
  		//store profile
  		$data['user_id'] 		= $user->id;
  		$data['id'] 			= $data['profile'];
		
		$this->store($data, 'profile');
		
		$profile_id = $this->_db->insertid();

  		if($data['id'] == 0){
  			//save images
  			if(intval($profile_id) != 0){
       			$query = 'UPDATE #__wrd_file SET product_id = '.$profile_id.' WHERE product_id = 0 AND user_id = '.$data['created_id'];
       			$this->_db->setQuery($query) ;
       			$this->_db->query() ;
  			}

       		//Give user point and store in database
       		if($fe == 1){
  				$type = 1 ;
  				$created_date = date("Y-m-d") ;
  				//send infos of account to user
                $data = $user->getProperties();
                $data['fromname']       = $config->get('fromname');
                $data['mailfrom']       = $config->get('mailfrom');
                $data['sitename']       = $config->get('sitename');
                $data['siteurl']        = str_replace('/administrator/', '/', JUri::base() ) ;
  				
	  		}
  			return $profile_id ;
  		}else{
  			//save images
       		$query = 'UPDATE #__wrd_file SET product_id = '.$data['id'].' WHERE product_id = 0 AND user_id = '.$data['created_id'];
       		$this->_db->setQuery($query);
       		$this->_db->query();
  		}
		
  		return $user->id;
  	}
	
	//reset password
	public function processResetRequest($data){
		jimport('joomla.user.helper');
		$config	= JFactory::getConfig();
		// Find the user id for the given email address.
		$db	= $this->getDbo();
		$query	= $db->getQuery(true);
		$query->select('id');
		$query->from('`#__users`');
		$query->where('`email` = '.$db->Quote($data));

		// Get the user object.
		$db->setQuery((string) $query);
		$userId = $db->loadResult();

		// Check for an error.
		if ($db->getErrorNum()) {
			$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $db->getErrorMsg()), 500);
			return false;
		}

		// Check for a user.
		if (empty($userId)) {
			$this->setError(JText::_('COM_USERS_INVALID_EMAIL'));
			return false;
		}

		// Get the user object.
		$user = JUser::getInstance($userId);

		// Make sure the user isn't blocked.
		if ($user->block) {
			$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
			return false;
		}

		// Make sure the user isn't a Super Admin.
		if ($user->authorise('core.admin')) {
			$this->setError(JText::_('COM_USERS_REMIND_SUPERADMIN_ERROR'));
			return false;
		}

		// Set the confirmation token.
		$token = JUtility::getHash(JUserHelper::genRandomPassword());
		$salt = JUserHelper::getSalt('crypt-md5');
		$hashedToken = md5($token.$salt).':'.$salt;

		$user->activation = $hashedToken;

		// Save the user to the database.
		if (!$user->save(true)) {
			return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500);
		}

		// Assemble the password reset confirmation link.
		$mode = $config->get('force_ssl', 0) == 2 ? 1 : -1;
		$link = 'index.php?option=com_wrd&view=profile&layout=confirm';

		// Put together the email template data.
		$data = $user->getProperties();
		$data['fromname']	= $config->get('fromname');
		$data['mailfrom']	= $config->get('mailfrom');
		$data['sitename']	= $config->get('sitename');
		$data['link_text']	= JRoute::_($link, false, $mode);
		$data['link_html']	= JRoute::_($link, true, $mode);
		$data['token']		= $token;

		$subject = JText::sprintf(
			'COM_USERS_EMAIL_PASSWORD_RESET_SUBJECT',
			$data['sitename']
		);

		$body = JText::sprintf(
			'COM_USERS_EMAIL_PASSWORD_RESET_BODY',
			$data['sitename'],
			$data['token'],
			$data['link_text']
		);

		// Send the password reset request email.
		$return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $user->email, $subject, $body);
		// Check for an error.
		if ($return !== true) {
			return new JException(JText::_('COM_USERS_MAIL_FAILED'), 500);
		}

		return true;
	}
	
	function processResetConfirm($data)
	{
		jimport('joomla.user.helper');
		// Find the user id for the given token.
		$db	= $this->getDbo();
		$query	= $db->getQuery(true);
		$query->select('activation');
		$query->select('id');
		$query->select('block');
		$query->from('`#__users`');
		$query->where('`username` = '.$db->Quote($data['username']));

		// Get the user id.
		$db->setQuery((string) $query);
		$user = $db->loadObject();

		// Check for an error.
		if ($db->getErrorNum()) {
			return new JException(JText::sprintf('COM_USERS_DATABASE_ERROR', $db->getErrorMsg()), 500);
		}

		// Check for a user.
		if (empty($user)) {
			$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
			return false;
		}

		$parts	= explode( ':', $user->activation );
		$crypt	= $parts[0];
		if (!isset($parts[1])) {
			$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
			return false;
		}
		$salt	= $parts[1];
		$testcrypt = JUserHelper::getCryptedPassword($data['token'], $salt);

		// Verify the token
		if (!($crypt == $testcrypt))
		{
			$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
			return false;
		}

		// Make sure the user isn't blocked.
		if ($user->block) {
			$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
			return false;
		}

		// Push the user data into the session.
		$app = JFactory::getApplication();
		$app->setUserState('com_wrd.profile.token', $crypt.':'.$salt);
		$app->setUserState('com_wrd.profile.user', $user->id);

		return true;
	}
	
	function processResetComplete($data)
	{
		// Get the token and user id from the confirmation process.
		$app	= JFactory::getApplication();
		$token	= $app->getUserState('com_wrd.profile.token', null);
		$userId	= $app->getUserState('com_wrd.profile.user', null);

		// Check the token and user id.
		if (empty($token) || empty($userId)) {
			return new JException(JText::_('COM_USERS_RESET_COMPLETE_TOKENS_MISSING'), 403);
		}

		// Get the user object.
		$user = JUser::getInstance($userId);

		// Check for a user and that the tokens match.
		if (empty($user) || $user->activation !== $token) {
			$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
			return false;
		}

		// Make sure the user isn't blocked.
		if ($user->block) {
			$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
			return false;
		}

		// Generate the new password hash.
		jimport('joomla.user.helper');
		$salt		= JUserHelper::genRandomPassword(32);
		$crypted	= JUserHelper::getCryptedPassword($data['password1'], $salt);
		$password	= $crypted.':'.$salt;

		// Update the user object.
		$user->password			= $password;
		$user->activation		= '';
		$user->password_clear	= $data['password1'];

		// Save the user to the database.
		if (!$user->save(true)) {
			return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500);
		}

		// Flush the user data from the session.
		$app->setUserState('com_wrd.profile.token', null);
		$app->setUserState('com_wrd.profile.user', null);

		return true;
	}
	
	function checkUser($uer_id, $username){
		$db = JFactory::getDbo();
		$condition = 0 ;
		if(!empty($uer_id)){
			$query = '
			SELECT id 
			FROM #__wrd_profile p
			LEFT JOIN #__users as u ON u.id = p.user_id
			WHERE u.user_id = "'.$uer_id.'"
			' ;
		}else{
			$query = '
			SELECT p.published 
			FROM #__wrd_profile p
			LEFT JOIN #__users as u ON u.id = p.user_id
			WHERE u.username = "'.$username.'"
			' ;
		}
		$db->setQuery($query) ;
		$user = $db->loadObject() ;
		return $user->published ;
	}
	
	//Export user list to excel
	function Export($cid = array()){
		global $mainframe ; 
		$mainframe = JFactory::getApplication();
		## Make DB connections
		$db    = JFactory::getDBO();
		JArrayHelper::toInteger($cid);
		$cids = implode( ',', $cid );

		$query = 'SELECT 
		p.prefix as Title,
		p.name_on_card as Fullname,
		p.dob as Birthday,
		p.member_id as Memberid,
		p.phone as Phone,
		p.p_email as Email,
		p.address as Address
		FROM #__wrd_profile as p
		WHERE published = 1 and id IN ( '.$cids.' )';
		$db->setQuery($query);
		$rows = $db->loadAssocList();
		
      ## If the query doesn't work..
      if (!$db->query() ){
         echo "<script>alert('Please report your problem.');
         window.history.go(-1);</script>\n";      
      }   
      
      ## Empty data vars
      $data = "" ;
      ## We need tabbed data
      $sep = "\t";
      
      $fields = (array_keys($rows[0]));
      
      ## Count all fields(will be the collumns
      $columns = count($fields);
      ## Put the name of all fields to $out. 
      for ($i = 0; $i < $columns; $i++) {
        $data .= $fields[$i].$sep;
      }
      
      $data .= "\n";
      
      ## Counting rows and push them into a for loop
      for($k=0; $k < count( $rows ); $k++) {
         $row = $rows[$k];
         $line = '';
         
         ## Now replace several things for MS Excel
         foreach ($row as $value) {
           $value = str_replace('"', '""', $value);
           $line .= '"' . $value . '"' . "\t";
         }
         $data .= trim($line)."\n";
      }
      
      $data = str_replace("\r","",$data);
      
      ## If count rows is nothing show o records.
      if (count( $rows ) == 0) {
        $data .= "\n(0) Records Found!\n";
      }
      ## Push the report now!
      $cur_date = date('d-m-Y') ; 
      $this->name = 'List_user_need_to_make_vipcard_'.$cur_date;
      header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename='".$this->name."'.csv");
      header("Pragma: no-cache");
      header("Expires: 0");
      header("Lacation: excel.htm?id=yes");
      print $data ;
      die();   
   }
   
   	public function activate($token,$memberid = 0)
   	{
	   	$config	= JFactory::getConfig();
	   	$userParams	= JComponentHelper::getParams('com_users');
	   	$db		= $this->getDbo();
	   
	   	// Get the user id based on the token.
	   	$db->setQuery(
	   			'SELECT `id` FROM `#__users`' .
	   			' WHERE `activation` = '.$db->Quote($token) .
	   			' AND `block` = 1' .
	   			' AND `lastvisitDate` = '.$db->Quote($db->getNullDate())
	   	);
	   	$userId = (int) $db->loadResult();
	   
	   	// Check for a valid user id.
	   	if (!$userId) {
	   		$this->setError(JText::_('COM_USERS_ACTIVATION_TOKEN_NOT_FOUND'));
	   		return false;
	   	}
	   
	   	// Load the users plugin group.
	   	JPluginHelper::importPlugin('user');
	   
	   	// Activate the user.
	   	$user = JFactory::getUser($userId);
	   
	   	$data = new stdClass();
	   	$data->id 	= null;
	   	$data->user_id 	= $user->id;
	   	$data->p_email = $user->email;
	   	$data->member_id = $memberid;
	   	$data->created_date = date('Y-m-d') ;
	   	
	   	$db->insertObject('#__wrd_profile', $data);
	   	
	   	$db->insertid();
	   	$query = 'UPDATE #__users SET name = "'.$memberid.'" , username = "'.$memberid.'" WHERE id='. $user->id;

	   	// Admin activation is on and user is verifying their email
	   	if (($userParams->get('useractivation') == 2) && !$user->getParam('activate', 0))
	   	{
	   		$uri = JURI::getInstance();
	   		jimport('joomla.user.helper');
	   
	   		// Compile the admin notification mail values.
	   		$data = $user->getProperties();
	   		$data['activation'] = JUtility::getHash(JUserHelper::genRandomPassword());
	   		$user->set('activation', $data['activation']);
	   		$data['siteurl']	= JUri::base();
	   		$base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
	   		$data['activate'] = $base.JRoute::_('index.php?option=com_users&task=registration.activate&token='.$data['activation'], false);
	   		$data['fromname'] = $config->get('fromname');
	   		$data['mailfrom'] = $config->get('mailfrom');
	   		$data['sitename'] = $config->get('sitename');
	   		$user->setParam('activate', 1);
	   		$emailSubject	= JText::sprintf(
	   				'COM_USERS_EMAIL_ACTIVATE_WITH_ADMIN_ACTIVATION_SUBJECT',
	   		$data['name'],
	   		$data['sitename']
	   		);
	   
	   		$emailBody = JText::sprintf(
	   				'COM_USERS_EMAIL_ACTIVATE_WITH_ADMIN_ACTIVATION_BODY',
	   		$data['sitename'],
	   		$data['name'],
	   		$data['email'],
	   		$data['username'],
	   		$data['siteurl'].'index.php?option=com_users&task=registration.activate&token='.$data['activation']
	   		);
	   
	   		// get all admin users
	   		$query = 'SELECT name, email, sendEmail' .
	   						' FROM #__users' .
	   						' WHERE sendEmail=1';
	   
	   		$db->setQuery( $query );
	   		$rows = $db->loadObjectList();
	   
	   		// Send mail to all superadministrators id
	   		foreach( $rows as $row )
	   		{
	   			$return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $row->email, $emailSubject, $emailBody);
	   
	   			// Check for an error.
	   			if ($return !== true) {
	   				$this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED'));
	   				return false;
	   			}
	   		}
   	}
   
   	//Admin activation is on and admin is activating the account
   	else if (($userParams->get('useractivation') == 2) && $user->getParam('activate', 0))
   	{
   		$user->set('activation', '');
   		$user->set('block', '0');
   
   		$uri = JURI::getInstance();
   		jimport('joomla.user.helper');
   
   		// Compile the user activated notification mail values.
   		$data = $user->getProperties();
   		$user->setParam('activate', 0);
   		$data['fromname'] = $config->get('fromname');
   		$data['mailfrom'] = $config->get('mailfrom');
   		$data['sitename'] = $config->get('sitename');
   		$data['siteurl']	= JUri::base();
   		$emailSubject	= JText::sprintf(
   				'COM_USERS_EMAIL_ACTIVATED_BY_ADMIN_ACTIVATION_SUBJECT',
   		$data['name'],
   		$data['sitename']
   		);
   
   		$emailBody = JText::sprintf(
   				'COM_USERS_EMAIL_ACTIVATED_BY_ADMIN_ACTIVATION_BODY',
   		$data['name'],
   		$data['siteurl'],
   		$data['username']
   		);
   
   		$return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody);
   
   		// Check for an error.
   		if ($return !== true) {
   			$this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED'));
   			return false;
   		}
   	}
   	else
   	{
   		$user->set('activation', '');
   		$user->set('block', '0');
   	}
   
   	// Store the user object.
   	if (!$user->save()) {
   		$this->setError(JText::sprintf('COM_USERS_REGISTRATION_ACTIVATION_SAVE_FAILED', $user->getError()));
   		return false;
   	}
   	
   	$db->setQuery($query)->query();
   	return $user;
   }
	
    public function getListProfiles ( $date_from, $date_to, $condition = '', $total = 0 ){
   		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
   		$search = $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string');	
   		if($total == 0){
   			$query = '
				select 
					p.id, p.prefix, p.user_id, p.f_name, p.l_name, p.published, p.created_date, p.dob,
					p.member_id, p.phone, p.address, p.c_addr, p.c_info, p.step, p.website, p.skype,
					p.yahoo, p.gtalk, p.social, p.msn, p.modify_date,p.job, job.name as job_name, p.job_prefix, p.o_job, u.name as created_per,
					pu.email, p.industry, p.department, p.education, p.o_club, p.income, p.hobbies, p.c_country,
					p.c_city, p.c_distric, ctry.name as ctry_country, cty.name as cty_city, dtric.name as dis_distric,
					p.referer, p.status, p.country_code, p.p_email, p.nationality, p.name_on_card, p.company_name,
					p.modify_by, p.delivery_date, p.pick_up_date
								
					FROM #__wrd_profile as p 
					LEFT JOIN #__users as pu ON pu.id = p.user_id 
					LEFT JOIN #__users as u ON u.id = p.created_id
					LEFT JOIN #__wrd_country as ctry ON ctry.id = p.country
					LEFT JOIN #__wrd_city as cty ON cty.id = p.city
					LEFT JOIN #__wrd_job as job ON job.id = p.job
					LEFT JOIN #__wrd_distric as dtric ON dtric.id = p.distric		
			' ;
   		}else{
   			$query = '
   				select 
					count(p.id) as total
					FROM #__wrd_profile as p 		
			' ;
   		}
		$query .= ' where (1) ' ;
		if(!empty($date_from)){
			$query .= ' and p.created_date >= "'.$date_from.'"'; 
		}
		if(!empty($date_to)){
			$query .= ' and p.created_date <= "'.$date_to.'" ' ; 
		}
		if(!empty($condition)){
			$query .= $condition ; 
		}
   		$search = JString::strtolower( $search );
		if ($search){
			$query .= ' and p.member_id LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ); 
		}
		
		$filter_order     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_author','filter_order','member_id' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir',  'filter_order_Dir', 'DESC' );
		
		if($total == 0){
			$query .= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
			$this->_db->setQuery($query, $this->_limitstart, $this->_limit );
			return $this->_db->loadObjectList();
		}else{
			$this->_db->setQuery($query) ;
			return $this->_db->loadObject();
		}
	}
	
	public function getPaging($total = 0){
		jimport('joomla.html.pagination');
		$this->paging = new JPagination( $total , $this->_limitstart, $this->_limit );
		return $this->paging ;
	}
	
	function getListRedemtion($condition = '', $total = 0){
		$mainframe = JFactory::getApplication() ;
		$db = JFactory::getDbo();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		if($total == 0){
			$query = '
			SELECT r.*, pro.name as pro_name 
			FROM #__wrd_redemption r 
			LEFT JOIN #__wrd_products pro ON pro.id = r.product_id
			LEFT JOIN #__wrd_profile p ON p.user_id = r.user_id 
			WHERE (1) ' ;
		}else{
			$query = 'SELECT count(id) as total FROM #__wrd_redemption r WHERE (1) ';
		}
		if(!empty($condition)){
			$query .= $condition ;
		}
		//filter by product
		$filter_product_id 	= $mainframe->getUserStateFromRequest( $context.$view.'product_id','product_id',-1,'int' );
		if ( $filter_product_id != -1 ){
			$query .= ' and r.product_id = '.$filter_product_id ;
		}
		
		//filter by outlet
		$filter_r_outlet 	= $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at',-1,'int' );
		if ( ($filter_r_outlet != -1) && !empty($filter_r_outlet) ){
			$query .= ' and p.pick_up_at = '.$filter_r_outlet ;
		}
		
		//filter by status of redemption
		$filter_r_status 	= $mainframe->getUserStateFromRequest( $context.$view.'status','status',-1,'int' );
		if (( $filter_r_status != -1 ) && !empty($filter_r_status) ){
			$query .= ' and r.status_of_redemption = '.$filter_r_status ;
		}
		
		//Filter by date_type && date
		$filter_type 	= $mainframe->getUserStateFromRequest( $context.$view.'filter_type','filter_type',-1,'int' );
		$filter_date 	= $mainframe->getUserStateFromRequest( $context.$view.'filter_date','filter_date',-1,'date' );
		if (( $filter_type != -1 ) && !empty($filter_type) ){
			switch ($filter_type){
				case '1':
					if(!empty($filter_date)){
						$query .= ' and r.exchange_date = "'.$filter_date.'"' ;
					}
					break ;
				case '2' :
					if(!empty($filter_date)){
						$query .= ' and r.pick_up_date = "'.$filter_date.'"' ;
					}
					break;
				case '3' :
					$filter_type = '' ;
					if(!empty($filter_date)){
						$query .= ' and r.status_of_redemption_date = "'.$filter_date.'" and r.status_of_redemption = 4 ' ;
					}
					break;
			}
		}
		
		//order
		$filter_order     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_author','filter_order','id' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir',  'filter_order_Dir', 'DESC' );
		$query 	.= ' ORDER BY '.$filter_order.' '.$filter_order_Dir ;
		
		if($total == 0){
			$db->setQuery($query, $this->_limitstart, $this->_limit );
			return $db->loadObjectList();
		}else{
			$db->setQuery($query);
			return $db->loadObject();
		}
	}
    
    public function checkStepRegistration($userId) {
        $sql = "
            SELECT
                `t`.user_id,
                `t`.step,
                `t`.id
            FROM #__wrd_profile `t`
            WHERE `t`.user_id = '".$userId."'
        ";        
        $this->_db->setQuery( $sql );
        $data = $this->_db->loadObject();
        return $data;
    }
    
    /**
     *  Update Registration Steps
     */
    public function updateStepRegistration($updateObj) 
    {
          	$user = &JFactory::getUser();
          	$step_link = $updateObj->step_link;
          	
          	unset($updateObj->step_link);
          	
            $result = $this->_db->updateObject('#__wrd_profile', $updateObj, 'id');    
            
            $pointFields = array();
            
            $sql = "
                SELECT *
                FROM #__wrd_log_register `t`
                WHERE `t`.id = '".$updateObj->user_id."'
                      AND `t`.step_no = '".$step_link."'
            ";
            $this->_db->setQuery($sql);
            $logRegister = $this->_db->loadObject();
            
            if(!is_null($logRegister)) {
                $logRegister = unserialize($logRegister->completefields);
                $pointFields = $logRegister;
                
                if(!empty($updateObj)) {
                   
                    foreach($updateObj as $key => $value) {
                        
                        if(($value != '' && $value != "0") || ($key == 'own_car')){
                            $update = true;
                            foreach($logRegister as $item) {
                                if($key == $item[0]) {
                                    $update = false;
                                }                
                            }
                            if($update) {
                                $point = self::getFieldPoint($key);
                                
								if($point->point > 0) {
                                    self::createPointForProfile($updateObj, $point, $user);
                                    $pointFields[] = array($key, $point->point);    
                                }        
                            }
                        }
                    }// end foreach UpdateObj
                     
                    $sql = " UPDATE #__wrd_log_register `t` SET `t`.completefields = '".serialize($pointFields)."' WHERE `t`.id = '".$updateObj->user_id."' AND `t`.step_no = ".$step_link;
                    $this->_db->setQuery($sql);
                    $this->_db->query();
                }
            }
            else {
            	//new member
                foreach($updateObj as $key => $value) {
                    if(($value != '' && $value != "0") || ($key == 'own_car')){
                        $point = $this->getFieldPoint($key);
                        
						if($point->point > 0) {
                            self::createPointForProfile($updateObj, $point, $user);
                            $pointFields[] = array($key, $point->point);    
                        }
                    }
                }
                
                /******* Create log registration *******/
                $obj = new stdClass;
                $obj->id = $updateObj->user_id;
                $obj->step_no = $step_link;
                $obj->completefields = serialize($pointFields);
                $this->_db->insertObject('#__wrd_log_register', $obj);            
            }                        
        
            
            
    }
    
    public function getTotalStepReg()
    {
    	$db = &JFactory::getDbo();
    	$user = &JFactory::getUser();
    	
    	// get total step
    	$query = 'SELECT count(*) as total FROM `#__wrd_log_register` where id = '.$user->id;
    	$db->setQuery($query);
    	return $db->loadObject()->total;
    }
    
    private function createPointForProfile($updateObj, $point, $user)
    {
    	$created_date = date('Y-m-d');
    	$expire  = WrdHelper::calculateExpiredDate($created_date);
    	
  		if($expire != '0000-00-00'){
    		if(strtotime($expire.' 23:59:59') < time())
    			$expired = 1;
    		else
    			$expired =  0;
  		}
    	else
    		$expired =  0;
    	
		$obj = new stdClass;
		$obj->id = null;
		$obj->user_id = $updateObj->user_id;
		$obj->transaction = $point->id;
		$obj->type = '1';
		$obj->point = $point->point;
		$obj->remain = $point->point;
		$obj->expire = $expire;
		$obj->expired = $expired;
		$obj->des = "Field name: ".$point->caption;
		$obj->created_id = $user->id ;
		$obj->created_date = date('Y-m-d H:m:s') ;
		$obj->modify_id = '';
		$obj->modify_date = '';
		$obj->flagConvert = '1';
		$obj->crpoint_id = $point->id;
			
		$this->_db->insertObject('#__wrd_point', $obj);
		
    }
    
    private function getFieldPoint($fieldName){
        $sql = "
            SELECT
                `t`.POINT AS `point`,
				`t`.id AS `id`,
				`t`.caption
            FROM #__wrd_crpoint `t`
            WHERE `t`.field = '".$fieldName."'
                  AND `t`.state = 1
        ";
		//echo $sql;die;
        $this->_db->setQuery($sql);
        $result = $this->_db->loadObject();
		
        return (!is_null($result) ? $result : 0);
    }    
    
}